package com.sale.succ.datacomp.produce;

import static com.sale.succ.utils.TraderHelper.getLabel;

import java.util.ArrayList;
import java.util.HashMap;

import com.sale.succ.components.DefInput;
import com.sale.succ.components.MessDialog;
import com.sale.succ.interfaces.ValueGetter;
import com.sale.succ.objects.LastSalesObj;
import com.sale.succ.objects.ProductObj;
import com.sale.succ.objects.Session;
import com.sale.succ.system.txt.ObjectsProvider;
import com.sale.succ.utils.DateFormatter;
import com.sale.succ.utils.Logger;
import com.sale.succ.utils.SystemConstants;
import com.sale.succ.utils.TraderConstants;
import com.sale.succ.utils.TraderHelper;

import eve.fx.Color;
import eve.fx.Point;
import eve.ui.Control;
import eve.ui.Gui;
import eve.ui.table.TableCellAttributes;
import eve.ui.table.TableModel;

public class ProduceTableModel extends TableModel implements ValueGetter{
	private String HEADERS[] = { getLabel(TraderConstants.PRODUCE_NAME),
			getLabel(TraderConstants.PRODUCE_ORDER1_COL),
			getLabel(TraderConstants.PRODUCE_ORDER2_COL),
			getLabel(TraderConstants.PRODUCE_ORDER_COL) };
	public static final int NAME_COL = 0;
	public static final int ORDER1_COL = 1;
	public static final int ORDER2_COL = 2;
	public static final int ORDER_COL = 3;

	HashMap row2prodId;
	HashMap lastSale;
	private MessDialog loadingDialog;
	private HashMap currentRests = new HashMap();

	public ProduceTableModel() {
		loadingDialog = new MessDialog(getLabel(TraderConstants.LOADING),
				MessDialog.NOB);

		loadingDialog.exec();
		try {
			initData();
		} finally {
			loadingDialog.close(0);
		}
		numRows = row2prodId.size();

		numCols = HEADERS.length;
		hasRowHeaders = false;
		hasColumnHeaders = true;
		fillToEqualWidths = true;
		canMoveColumnHeaders = false;
		canHScroll = true;
		selectRowWhenEditing = true;

		// allColumnsSameSize = true;

	}

	public HashMap getRests() {
		return currentRests;
	}

	private void initData() {
		try{
			row2prodId = new HashMap();
			ObjectsProvider.getInstance().getMappingProductsToTradeMarkCollection();
			ArrayList productIds = ObjectsProvider.getInstance().getMappingProductsToTradeMarkCollection().get(Session.getInstance().getTradeId());
	
			for (int i = 0; i < productIds.size(); i++) {
				row2prodId.put(String.valueOf(i), productIds.get(i));
			}
	
			lastSale = ObjectsProvider.getInstance().getLastSalesCollection(Session.getInstance().getClientId());			
		}catch(Exception ex){
			Logger.error(ex.getMessage());
		}

	}

	public int itemCount() {
		return row2prodId.size();
	}

	/*
	 * public int search(String find) { int result = -1; find =
	 * find.toLowerCase().trim(); for (int i = 0; i < produces.size(); ++i) {
	 * String name = ((Produce) produces.get(i)).getName();
	 * 
	 * if (name.toLowerCase().startsWith(find)) { result = i; break; } }
	 * 
	 * return result; }
	 */

	public int calculateColWidth(int col) {
		if (col == -1)
			return 0;

		if (col != NAME_COL) {
			return (Gui.getScreenSize().width - NAME_COL_WIDTH - SystemConstants.SCROLL_BUTTON_W)
					/ (HEADERS.length - 1);
		}

		return NAME_COL_WIDTH;

	}

	private final int NAME_COL_WIDTH = (int) (Gui.getScreenSize().width * 0.4);

	public int calculateRowHeight(int row) {
		return 20;

	}

	/*
	 * public Object getObjForTooltip(int row) { return produces.get(row); }
	 */

	public ArrayList getData(int row) {
		String prodId = (String) row2prodId.get(String.valueOf(row));

		ArrayList list = new ArrayList();

		ProductObj product = (ProductObj) ObjectsProvider.getInstance()
				.getProductCollection().get(prodId);
		LastSalesObj lSale = (LastSalesObj) lastSale.get(prodId);

		if (lSale == null)
			return null;

		list.add(product.getProductName());
		list.add((Integer.parseInt(product.getRest())
						- product.getGlobalRest() - Integer.parseInt(lSale
						.getOrder()))
						+ "");
		list.add(lSale.getPrice() + "");
		return list;
	}
	
	public String getOrder(int row) {
		String prodId = (String) row2prodId.get(String.valueOf(row));
		LastSalesObj lSale = (LastSalesObj) lastSale.get(prodId);
		return lSale.getOrder();
	}

	public Object getCellData(int row, int col) {
		if (row == -1) {
			return HEADERS[col];
		}
		String prodId = (String) row2prodId.get(String.valueOf(row));
		LastSalesObj lSale = (LastSalesObj) lastSale.get(prodId);
		ProductObj product = (ProductObj) ObjectsProvider.getInstance()
				.getProductCollection().get(prodId);
		switch (col) {
		case NAME_COL:
			return product == null ? "-" : product.getProductName();
		case ORDER1_COL:
			return lSale == null ? "-" : lSale.getSales1() + "";
		case ORDER2_COL:
			return lSale == null ? "-" : lSale.getSales2() + "";
		case ORDER_COL:
			return lSale == null ? "-" : lSale.getOrder() + "";
		default:
			return "";
		}

	}

	/*
	 * public String getMark(int r) { return ((Produce) produces.get(r +
	 * currentNumber)).getName(); }
	 */

	public TableCellAttributes getCellAttributes(int row, int col,
			boolean isSelected, TableCellAttributes ta) {
		ta = super.getCellAttributes(row, col, isSelected, ta);
		if (row != -1) {
			ta.clipCellData = true;
			ta.anchor = WEST;
		}
		if (isSelected) {
			ta.foreground = Color.Black;
			ta.fillColor = TraderConstants.TBLMODEL_SELCOL;
		} else {
			ta.foreground = Color.DarkGray;
		}
		ta.alignment = TableCellAttributes.RIGHT;
		return ta;
	}

	private DefInput editor;

	private DefInput getEditor() {
		if (editor == null) {
			editor = new DefInput();
		}
		return editor;
	}

	protected Control getControlFor(int row, int col) {

		/*if (col == ORDER_COL && row != -1) {
			LastSalesObj lSale = (LastSalesObj) lastSale.get(row2prodId
					.get(String.valueOf(row)));
			if (lSale == null) {
				getEditor().setText("0");
			} else {
				getEditor().setText(lSale.getOrder());
			}

			return getEditor();
		} */
		return null;
	}

	public ArrayList getOrders() {
		ArrayList orders = new ArrayList();
		for (int i = 0; i < row2prodId.size(); i++) {
			String prodId = (String) row2prodId.get(String.valueOf(i));
			LastSalesObj lSale = (LastSalesObj) lastSale.get(prodId);
			if (lSale == null)
				continue;
			if (lSale.getOrder().length() != 0 && !lSale.getOrder().equals("0")) {
				ArrayList order = new ArrayList();
				order.add(Session.getInstance().getClientId());
				order.add(Session.getInstance().getTradeId());
				order.add(prodId);
				order.add(lSale.getPrice());
				order.add(lSale.getOrder());
				order.add(Session.getInstance().getFw());
				order.add(DateFormatter.dateToString(Session.getInstance()
						.getGiveDate(), "."));
				order.add(String
						.valueOf(Session.getInstance().isCertificates()));
				order.add(DateFormatter.dateToString(Session.getInstance()
						.getPayDate(), "."));
				order.add(String.valueOf(Session.getInstance()
						.isMoneyCondition()));
				order.add(String.valueOf(Session.getInstance().isTablet()));
				order.add(String.valueOf(Session.getInstance().isExchange()));
				String notes = Session.getInstance().getNotes();
				notes = notes.length() > 80 ? notes.substring(0, 80) : notes;
				if (notes.length() == 0)
					notes = "null";
				order.add(notes);
				order.add(String.valueOf(Session.getInstance().isAsFact()));
				orders.add(order);
			}
		}
		return orders;
	}

	
	
	/*protected void notifyDataChange(Point cell) {
		try {
			if (cell.y == -1)
				return;
			String prodId = (String) row2prodId.get(String.valueOf(cell.y));

			LastSalesObj lSale = (LastSalesObj) lastSale.get(prodId);

			if (lSale == null)
				return;

			int previousOrder = Integer.parseInt(lSale.getOrder());
			int currentOrder = Integer.parseInt(getEditor().getText());

			lSale.setOrder(currentOrder + "");

			double sum = 0;
			for (int i = 0; i < row2prodId.size(); i++) {
				lSale = (LastSalesObj) lastSale.get(row2prodId.get(String
						.valueOf(i)));
				if (lSale == null)
					continue;
				if (Integer.parseInt(lSale.getOrder()) != 0) {
					sum += Integer.parseInt(lSale.getOrder())
							* Double.parseDouble(lSale.getPrice());
				}
			}

			ArrayList list = new ArrayList();

			ProductObj product = (ProductObj) ObjectsProvider.getInstance()
					.getProductCollection().get(prodId);
			lSale = (LastSalesObj) lastSale.get(prodId);
			if (lSale == null)
				return;

			currentRests.put(product.getId(), (currentOrder - previousOrder)
					+ "");

			list.add(product.getProductName());
			list.add(Integer.parseInt(product.getRest())
					- product.getGlobalRest()
					- Integer.parseInt(lSale.getOrder()) + "");
			list.add(lSale.getPrice() + "");
			list.add(sum + "");

			((ProduceTable) table).notifyListener(list, true);
		} catch (Exception e) {
			Logger.error(e.getMessage());
			new MessDialog(TraderHelper
					.getLabel(TraderConstants.MSG_WRONG_ORDER)).showAsPopup();
		}
	} */	
	
	public void orderChanged(Point cell, String value){
		try {
			if (cell.y == -1)
				return;
			String prodId = (String) row2prodId.get(String.valueOf(cell.y));

			LastSalesObj lSale = (LastSalesObj) lastSale.get(prodId);

			if (lSale == null)
				return;

			int previousOrder = Integer.parseInt(lSale.getOrder());
			int currentOrder = Integer.parseInt(value);

			lSale.setOrder(currentOrder + "");

			double sum = 0;
			for (int i = 0; i < row2prodId.size(); i++) {
				lSale = (LastSalesObj) lastSale.get(row2prodId.get(String
						.valueOf(i)));
				if (lSale == null)
					continue;
				if (Integer.parseInt(lSale.getOrder()) != 0) {
					sum += Integer.parseInt(lSale.getOrder())
							* Double.parseDouble(lSale.getPrice());
				}
			}

			ArrayList list = new ArrayList();

			ProductObj product = (ProductObj) ObjectsProvider.getInstance()
					.getProductCollection().get(prodId);
			lSale = (LastSalesObj) lastSale.get(prodId);
			if (lSale == null)
				return;

			currentRests.put(product.getId(), (currentOrder - previousOrder)
					+ "");

			list.add(product.getProductName());
			list.add(Integer.parseInt(product.getRest())
					- product.getGlobalRest()
					- Integer.parseInt(lSale.getOrder()) + "");
			list.add(lSale.getPrice() + "");
			list.add(sum + "");

			((ProduceTable) table).notifyListener(list, true);
		} catch (Exception e) {
			Logger.error(e.getMessage());
			new MessDialog(TraderHelper
					.getLabel(TraderConstants.MSG_WRONG_ORDER)).showAsPopup();
		}
	}

	
	public void setValue(Point cell, String value) {
		orderChanged(cell, value);
		
	}	

}
